package com.example.photo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.photo.common.AuthCheck;
import com.example.photo.common.BaseResponse;
import com.example.photo.common.ErrorCode;
import com.example.photo.constant.WorkStatus;
import com.example.photo.exception.BusinessException;
import com.example.photo.model.VO.ScoreWorkVO;
import com.example.photo.model.domain.Prize;
import com.example.photo.model.domain.Score;
import com.example.photo.model.domain.Work;
import com.example.photo.service.PrizeService;
import com.example.photo.service.ScoreService;
import com.example.photo.service.WorkService;
import com.example.photo.utils.JwtTokenUtils;
import com.example.photo.utils.ResultUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 打分接口
 *
 * @author Lwh
 * @time 2023/04/09 16:38
 */
@RestController
@RequestMapping("/score")
public class ScoreController {

    @Resource
    private WorkService workService;

    @Resource
    private ScoreService scoreService;

    @Resource
    private PrizeService prizeService;

    /**
     * 管理员查询当前账号未打分的作品（审核已通过）
     *
     * @param contestId 赛事id
     */
    @AuthCheck
    @GetMapping("/list")
    public BaseResponse<List<ScoreWorkVO>> listWorkToScore(@RequestParam long pageSize,
                                                           @RequestParam long pageNum,
                                                           @RequestParam Integer contestId,
                                                           HttpServletRequest request) {
        if (contestId < 1) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //根据赛事id查出所有已通过的作品
        QueryWrapper<Work> workWrapper = new QueryWrapper<>();
        workWrapper.eq("contest_id", contestId);
        workWrapper.eq("is_pass", WorkStatus.PASS);
        List<Work> workList = workService.page(new Page<>(pageNum, pageSize), workWrapper).getRecords();
        //若没有已通过审核的作品
        if (workList.size() == 0) {
            return ResultUtils.success(new ArrayList<>());
        }

        //过滤掉存在当前账号打分记录的作品
        Integer userId = Integer.valueOf(request.getHeader(JwtTokenUtils.USERID_HEADER));
        List<ScoreWorkVO> workVOList = workList.stream().filter(work -> {
            QueryWrapper<Score> scoreWrapper = new QueryWrapper<>();
            scoreWrapper.eq("work_id", work.getWorkId());
            scoreWrapper.eq("scorer_id", userId);
            return scoreService.count(scoreWrapper) == 0;
        }).map(ScoreWorkVO::new).peek(scoreWorkVO -> {
            Integer prizeId = scoreWorkVO.getPrizeId();
            Prize prize = prizeService.getById(prizeId);
            if (prize != null) {
                scoreWorkVO.setPrizeName(prize.getPrizeName());
            }
        }).collect(Collectors.toList());

        return ResultUtils.success(workVOList);
    }

    /**
     * 管理员给某个作品打分（没打过就增，打过就改）
     *
     * @param workId 作品id
     * @param score  分数
     */
    @AuthCheck
    @PostMapping("/upload")
    public BaseResponse<Boolean> scoreForWork(@RequestParam Integer workId,
                                              @RequestParam Integer score,
                                              HttpServletRequest request) {
        if (workId < 1 || score < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Integer userId = Integer.valueOf(request.getHeader(JwtTokenUtils.USERID_HEADER));
        scoreService.doScore(workId, userId, score);
        return ResultUtils.success(true);
    }
}
